<?php
class Model
{
	public $assoc = array();
	
	private $table, $query, $result = false, $index = 0, $foreign = array();
	
	public function __construct($raw=null)
	{
		$this->table = get_class($this);
		
		if(is_numeric($raw))
		{
			if($data = db::fetch(db::query('SELECT * FROM `'.DB_PREFIX.$this->table.'` WHERE `id`='.$raw), 'assoc'))
			{
				foreach($data as $key=>$value)
				{
					$this->assoc[$key] = $value;
				}
			}
		} elseif(is_array($raw))
		{
			if(isset($raw['id']))
			{
				foreach($raw as $key=>$value)
				{
					$this->assoc[$key] = $value;
				}
			} else
			{
				foreach($raw as $key=>&$value)
				{
					$this->assoc[$key] = $value;
					
					$value = db::escape($value);
				}
				
				db::query('INSERT INTO `'.DB_PREFIX.$this->table.'` (`'.implode('`, `', array_keys($raw)).'`) VALUES ("'.implode('", "', array_values($raw)).'")');
				
				$this->assoc['id'] = db::last_id();
			}
		} elseif(is_string($raw))
		{
			$this->query = ' '.$raw;
		}
	}
	
	public function query($string)
	{
		$this->query .= ' '.$string;
	}
	
	public function count()
	{
		$result = db::fetch(db::query('SELECT COUNT(*) AS `total` FROM `'.DB_PREFIX.$this->table.'`'.$this->query));
		
		return (int) $result['total'];
	}
	
	public function fetch(&$i=false)
	{
		if(!$this->result) $this->result = db::query('SELECT * FROM `'.DB_PREFIX.$this->table.'`'.$this->query);
		
		$i = $this->index;
		
		if($row = db::fetch($this->result, 'assoc'))
		{
			$i = ++$this->index;
			
			return new $this->table($row);
		}
		
		return false;
	}
	
	public function __get($key)
	{
		if(isset($this->assoc[$key])) return $this->assoc[$key];
		
		if(isset($this->assoc[$key.'_id']))
		{
			if(!isset($this->foreign[$key])) $this->foreign[$key] = new $key($this->assoc[$key.'_id']);
			
			return $this->foreign[$key];
		}
	}
	
	public function __set($key, $value)
	{
		$this->assoc[$key] = $value;
		
		if(isset($this->assoc['id']))
		{
			db::query('UPDATE `'.DB_PREFIX.$this->table.'` SET `'.$key.'`="'.db::escape($value).'" WHERE `id`='.$this->id);
		}
	}
}